package com.qiguliuxing.dts.admin.service;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.admin.dao.IordersAll;
import com.qiguliuxing.dts.admin.dao.IordersTemplate;
import com.qiguliuxing.dts.core.util.ResponseUtil;
import com.qiguliuxing.dts.db.domain.DailyOrder;
import com.qiguliuxing.dts.db.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminDailyOrderService {
    private static final Logger logger = LoggerFactory.getLogger(AdminGoodsService.class);

    @Autowired
    private IorderService iorderService;
    private IoralSolutionService ioralSolutionService;

    private IoralRawService ioralRawService;

    private SplitListService splitListService;

    private PackagesService packagesService;

    @Autowired
    private DailyOrderService dailyOrderService;


    public Object list(String customerName,String startTime,String endTime,/*DailyOrder dailyOrder,*/ Integer page, Integer limit,String sort,String order) {
//        try {
        logger.info("【请求结束】订单管理->仪器列表->查询,结果:{}", limit);
        List<DailyOrder> dailyOrderList = dailyOrderService.querySelective(customerName,startTime,endTime,/*dailyOrder,*/ page, limit,sort,order);
        long total = PageInfo.of(dailyOrderList).getTotal();
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", dailyOrderList);
        logger.info("【请求结束】碘订单管理->仪器列表->查询,响应结果:{}", JSONObject.toJSONString(data));
        return ResponseUtil.ok(data);

    }


    public Object listNow(List<IordersTemplate> iordersTemplates, int i, int i1) {
//        try {
        logger.info("【请求结束】订单管理->仪器列表->查询,结果:{}");
        /*List<DailyOrder> dailyOrderList = dailyOrderService.querySelective(dailyOrder, page, size);*/
        long total = PageInfo.of(iordersTemplates).getTotal();
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", iordersTemplates);
        logger.info("【请求结束】碘订单管理->仪器列表->查询,响应结果:{}", JSONObject.toJSONString(data));
        return ResponseUtil.ok(data);

    }


    private Object validate(IordersAll iordersAll) {
//        DailyOrder Instrument = InstrumentAll.getInstrument();
//        String name = Instrument.getInstrumentName();
//        if (StringUtils.isEmpty(name)) {
//            return ResponseUtil.badArgument();
//        }
//        Integer InstrumentType = Instrument.getInstrumentType();
//        if (StringUtils.isEmpty(InstrumentType)) {
//            return ResponseUtil.badArgument();
//        }
        // 品牌商可以不设置，如果设置则需要验证品牌商存在
        /*String InstrumentLink = Instrument.getInstrumentLink();
        if (InstrumentLink != null && InstrumentLink != "") {
            if (InstrumentService.findById(Instrument.getId()) == null) {
                return ResponseUtil.badArgumentValue();
            }
        }*/

        /*IordersMod[] mods = InstrumentAll.getInstrumentMod();*/
        /*for (IordersMod mod : mods) {
            Integer id = mod.getId();
            if (id != null && id != 0) {
                if (InstrumentModService.findById(mod.getId()) == null) {
                    return ResponseUtil.badArgumentValue();
                }
            }
            String content = mod.getContent();
            if (StringUtils.isEmpty(content)) {
                return ResponseUtil.badArgument();
            }
            String InstrumentName = mod.getInstrumentName();
            if (StringUtils.isEmpty(InstrumentName)) {
                return ResponseUtil.badArgument();
            }

        }*/


        return null;
    }

    /**
     * s
     * 编辑商品
     * <p>
     * TODO 目前商品修改的逻辑是 1. 更新Dts_goods表 2.
     * 逻辑删除Dts_goods_specification、Dts_goods_attribute、Dts_goods_product 3.
     * 添加Dts_goods_specification、Dts_goods_attribute、Dts_goods_product
     * <p>
     * 这里商品三个表的数据采用删除再添加的策略是因为 商品编辑页面，支持管理员添加删除商品规格、添加删除商品属性，因此这里仅仅更新是不可能的，
     * 只能删除三个表旧的数据，然后添加新的数据。 但是这里又会引入新的问题，就是存在订单商品货品ID指向了失效的商品货品表。
     * 因此这里会拒绝管理员编辑商品，如果订单或购物车中存在商品。 所以这里可能需要重新设计。
     */
    @Transactional
    public Object update(IordersAll iordersAll) {
        /*Object error = validate(InstrumentAll);
        if (error != null) {
            return error;
        }*/
        DailyOrder dailyOrder = iordersAll.getDailyOrder();
        /*IordersMod[] InstrumentMods = InstrumentAll.getInstrumentMod();*/


        Integer id = dailyOrder.getId();
        // 检查是否存在购物车商品或者订单商品
        // 如果存在则拒绝修改商品。
      /*  if (orderGoodsService.checkExist(id) || cartService.checkExist(id)) {
            logger.error("商品管理->商品管理->编辑错误:{}", GOODS_UPDATE_NOT_ALLOWED.desc());
            return AdminResponseUtil.fail(GOODS_UPDATE_NOT_ALLOWED);
        }*/

        // 将生成的分享图片地址写入数据库
/*        String url = qCodeService.createGoodShareImage(null,goods.getId().toString(), goods.getPicUrl(), goods.getName(),goods.getCounterPrice(),goods.getRetailPrice());
        goods.setShareUrl(url);*/
/*
        // 商品基本信息表Dts_goods
       // /* if (InstrumentService.updateById(Instrument) == 0) {
            // logger.error("商品管理->商品管理->编辑错误:{}", "更新数据失败");
            throw new RuntimeException("更新数据失败");
        }*/
        if (dailyOrderService.updateById(dailyOrder) == 0) {
            logger.error("碘131订单管理->碘131订单管理->编辑错误:{}", "更新数据失败");
            throw new RuntimeException("更新数据失败");
        }
        /*Integer gid = Instrument.getId();
        InstrumentModService.deleteById(gid);*/
    /*    attributeService.deleteByGid(gid);
        productService.deleteByGid(gid);*/

    /*    // 商品规格表Dts_goods_specification
        for (DtsGoodsSpecification specification : specifications) {
            specification.setGoodsId(goods.getId());
            specificationService.add(specification);
        }

        // 商品参数表Dts_goods_attribute
        for (DtsGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(goods.getId());
            attributeService.add(attribute);
        }

        // 商品货品表Dts_product
        for (DtsGoodsProduct product : products) {
            product.setGoodsId(goods.getId());
            productService.add(product);
        }*/
        //qCodeService.createGoodShareImage(goods.getId().toString(), goods.getPicUrl(), goods.getName());

        logger.info("【请求结束】碘订单->订单管理->编辑,响应结果:{}", "成功!");
        return ResponseUtil.ok();
    }


    @Transactional
    public Object delete(DailyOrder dailyOrder) {
        Integer id = dailyOrder.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }

        Integer gid = dailyOrder.getId();
        dailyOrderService.deleteById(gid);
        /*InstrumentMaintainService.deleteById(gid);*/

        logger.info("【请求结束】仪器管理->仪器管理->删除,响应结果:{}", "成功!");
        return ResponseUtil.ok();
    }

    @Transactional
    public Object create(IordersAll iordersAll) {
       /* Object error = validate(InstrumentAll);
        if (error != null) {
            return error;
        }*/

        DailyOrder dailyOrder = iordersAll.getDailyOrder();
        dailyOrder.setId((int) (IdUtil.getSnowflake().nextId() / 1000));
        dailyOrder.setDate(LocalDate.now());
        dailyOrder.setCustomerName(iordersAll.getDailyOrder().getCustomerName());

        dailyOrderService.add(dailyOrder);




        logger.info("【请求结束】碘订单->上架,响应结果:{}", "成功!");
        return ResponseUtil.ok();
    }


    public Object detail(Integer id) {
        DailyOrder dailyOrder = dailyOrderService.findById(id);

        /*List<IordersMaintain> mods = InstrumentMaintainService.queryByDid(id);*/
     /*   List<DtsGoodsSpecification> specifications = specificationService.queryByGid(id);
        List<DtsGoodsAttribute> attributes = attributeService.queryByGid(id);*/

        //用于展示商品归属的类目（页面级联下拉控件数据展示）
    /*    Integer categoryId = goods.getCategoryId();
        DtsCategory category = categoryService.findById(categoryId);*/
     /*   Integer[] categoryIds = new Integer[] {};
        if (category != null) {
            Integer parentCategoryId = category.getPid();
            categoryIds = new Integer[] { parentCategoryId, categoryId };
        }*/

        Map<String, Object> data = new HashMap<>();
        data.put("dailyOrder", dailyOrder);
        /*data.put("mods", mods);*/
 /*       data.put("products", products);
        data.put("attributes", attributes);
        data.put("categoryIds", categoryIds);*/

        logger.info("【请求结束】仪器管理->仪器管理->详情,响应结果:{}", "成功!");
        logger.info("hahahhaa");
        return ResponseUtil.ok(data);
    }


}
